package com.doyens.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doyens.common.CustomException;
import com.doyens.dto.SetmealDto;
import com.doyens.entity.Setmeal;
import com.doyens.entity.SetmealDish;
import com.doyens.mapper.SetmealMapper;
import com.doyens.service.SetmealDishService;
import com.doyens.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.security.auth.callback.LanguageCallback;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;


    //保存套餐信息
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息 操作  setmeal表 执行insert操作
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item) ->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        //保存套餐下的菜品表,  操作 setmeal_dish表, 执行insert操作
        setmealDishService.saveBatch(setmealDishes);

    }

    /**
     * 删除套餐
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //1.查询套餐状态, 确定是否可以删除   select * from emp where id in(1,2,3,4,5);
        LambdaQueryWrapper<Setmeal>  queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);
        if (count > 0){
            //2.如果不能删除,抛出一个业务异常
            throw new CustomException("套菜在售卖中,不能删除!");
        }
        //3.如果可以删除,先删除套餐表数据,
        this.removeByIds(ids);

        //再删除关系表数据  setmeal_dish
        LambdaQueryWrapper<SetmealDish>  dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(dishLambdaQueryWrapper);





    }
}
